import { Component, ChangeDetectorRef } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';
import { AppService } from './../../app/app.serve';
import { PublicCompoentsProvider } from './../../providers/public-compoents/public-compoents';
import { UserRechargePage } from './../user-recharge/user-recharge';
import { Storage } from '@ionic/storage';



let self;



/**
 * Generated class for the GoodsinfoPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-goodsinfo',
  templateUrl: 'goodsinfo.html',
})
export class GoodsinfoPage {

  goodId = '';
  goodInfo: any = [];//商品详情
  buyTypeNum: number = 1;  //购买单双类型
  buyBigOrSmall: number = 1;// 购买大小类型
  buyNum;
  buyNum1;
  buyNum2;
  buyNum_input: any = '';//自主输入数量
  showBuyNum_input = false;//是否显示自主输入框
  onInput = false;//是否在自主输入数量
  price: number;//单价
  num: number = 1;//购买数量
  totalPrice: number;// 单一玩法的总价
  order_all_prices: number;//提交订单时候的总价
  res: any = [];
  intervall: any = '';
  intervall2: any = '';
  prev_awardnum;
  resData = [];
  countdown = {
    minutes: '00',
    seconds: '00',
    Milliseconds: '00'
  }
  money = '';//账户余额
  userId = '';
  public nextOpenTime: number;//剩余的开奖时间
  public hasBindTel;//是否绑定了手机号
  public downTime = 0;
  public milliseconds = 0;
  public runMilliseconds = false;//是否模拟毫秒倒计时

  constructor(public storage: Storage, public PublicProvider: PublicCompoentsProvider, public changeDetectorRef: ChangeDetectorRef, public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public appService: AppService) {
    self = this;
    this.goodId = this.navParams.get('id');
    this.userId = this.navParams.get('userId');
    // 虚拟商品参数
    this.buyNum1 = [
      { num: 1, isPicked: true },
      { num: 5, isPicked: false },
      { num: 10, isPicked: false },
      { num: 20, isPicked: false },
      { num: 30, isPicked: false },
      { num: 50, isPicked: false },
      { num: 80, isPicked: false },
      { num: 100, isPicked: false },
    ]
    // 实物商品参数
    this.buyNum2 = [
      { num: 1, isPicked: true },
      { num: 2, isPicked: false },
      { num: 3, isPicked: false },
      { num: 4, isPicked: false },
      { num: 5, isPicked: false },
      { num: 6, isPicked: false },
      { num: 7, isPicked: false },
      { num: 8, isPicked: false },
      { num: 9, isPicked: false },
      { num: 10, isPicked: false },
    ]
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad GoodsinfoPage');
  }

  ngOnInit() {
    this.getGoodInfo();
  }
  ionViewWillEnter() {
    if (this.intervall !== '') { clearInterval(this.intervall) };
    if (this.intervall2 !== '') { clearInterval(this.intervall2) };
    this.lottery();
    this.getUserInfo();
  }
  onLeave() {
    if (this.intervall !== '') { clearInterval(this.intervall) };
    if (this.intervall2 !== '') { clearInterval(this.intervall2) };
  }

  // 取消操作按钮
  cancel() {
    this.onLeave();
    var data = { 'status': false }
    this.viewCtrl.dismiss(data);
  }
  // 购买单双类型
  buyType(buyType: number) {
    if (this.buyTypeNum == buyType) {
      this.buyTypeNum = 0
    } else {
      this.buyTypeNum = buyType
    }
    this.all_price();
    console.log('单双类型 0未选 1单 2双：', this.buyTypeNum)
  }
  //购买大小类型
  buyType2(buyType2: number) {
    if (this.buyBigOrSmall == buyType2) {
      this.buyBigOrSmall = 0
    } else {
      this.buyBigOrSmall = buyType2
    }
    this.all_price();
    console.log('大小类型 0未选 1小 2大：', this.buyBigOrSmall)
  }
  // 购买数量
  buyNumF(i: number) {
    console.log(i)
    this.onInput = false;
    this.buyNumF2();
    this.buyNum[i].isPicked = true;
    console.log('选择的购买数量：', this.buyNum[i].num)
    console.log('输入的购买数量：', this.buyNum_input)
    this.num = this.buyNum[i].num;
    this.all_price();
  }
  // 选择数量失焦
  buyNumF2() {
    this.buyNum.forEach(buy => {
      buy.isPicked = false;
    });
  }
  //输入购买数量
  buyNum_inputF() {
    if (this.buyNum_input !== null && this.buyNum_input !== '' && this.buyNum_input !== 0) {
      if (this.buyNum_input > 10000) {
        this.buyNum_input = ''
        this.totalPrice = 0
      } else {
        console.log('输入的购买数量：', this.buyNum_input = Math.ceil(this.buyNum_input))
        this.num = this.buyNum_input;
        this.all_price();
      }
    }
  }
  // 开始输入购买数量
  onFocus() {
    this.buyNumF2();
    this.onInput = true;
    this.num = this.buyNum_input;
    this.all_price();
  }
  // 离开输入购买数量
  onBlur() {
    if (this.buyNum_input == null || this.buyNum_input == '' || this.buyNum_input == 0) {
      this.buyNum_input = 1
    }
    this.buyNum_inputF();
    console.log('结束输入数量')
  }
  // 单一玩法的总价计算
  all_price() {
    if (this.buyTypeNum == 0 && this.buyBigOrSmall == 0) {
      this.totalPrice = 0
    } else {
      this.price = Number(this.price)
      this.num = Number(this.num)
      this.totalPrice = this.num * this.price
    }

  }
  //订单提交时候 判断最后总价
  // buyTypeNum: number = 1;  //购买单双类型
  // buyBigOrSmall: number = 1;// 购买大小类型
  order_all_price() {
    if (this.buyTypeNum == 0 && this.buyBigOrSmall == 0) {
      this.order_all_prices = 0;
    }
    if ((this.buyTypeNum == 0 && this.buyBigOrSmall !== 0) || this.buyTypeNum !== 0 && this.buyBigOrSmall == 0) {
      this.order_all_prices = this.totalPrice
    }
    if (this.buyTypeNum !== 0 && this.buyBigOrSmall !== 0) {
      this.order_all_prices = this.totalPrice * 2
    }
  }
  //去充值
  Recharge() {
    this.navCtrl.push(UserRechargePage);
    this.onLeave();
    var data = { 'status': false };
    this.viewCtrl.dismiss(data);
  }
  // 商品详情
  getGoodInfo() {
    this.appService.post('/apibuyorder/goods_detail', { goods: 'goods', goodid: this.goodId }, res => {
      console.log(res);
      if (res.code == 1) {
        this.goodInfo;
        this.goodInfo = res.data;
        this.price = this.goodInfo.price;
        this.all_price();
        console.log('产品详情：', this.goodInfo, '商品类型：', this.goodInfo.is_product_type)
        if (this.goodInfo.is_product_type == '实物') {
          this.buyNum = this.buyNum2;
          this.showBuyNum_input = false;
        } else {
          this.buyNum = this.buyNum1;
          this.showBuyNum_input = true;
        }
      }
    })
  }
  // 开奖信息
  lottery() {
    this.appService.post('/apiindex/index_lottery_num', { lottery: 'lottery' }, res => {
      console.log('开奖信息:', res)
      this.res = res;
      if (this.res.code == 1) {
        this.resData = this.res.data;
        this.prev_awardnum = this.res.data.prev_awardnum.split(",");
        this.downTime = this.res.data.now_end_time - this.res.data.now_time;
        console.log('倒计时秒数：', this.downTime)
        this.setEndTime(this.downTime)
        console.log(`服务器时间：${this.res.data.now_time},结束之间：${this.res.data.now_end_time},开始时间：${this.res.data.now_start_time},当前期号:${this.res.data.now_issue}`)
        console.log('上期开奖号码：', this.prev_awardnum)
      }
    }, false)
  }
  CountDown(endTime) {
    clearInterval(this.intervall);
    clearInterval(this.intervall2);
    setTimeout(() => {
      self.setMilliseconds();
    }, 1500);
    this.intervall = setInterval(() => {
      let dat1 = (new Date()).getTime();
      let dat2 = (endTime - dat1) / 1000
      self.nextOpenTime = dat2;
      // console.log(dat2)
      if (dat2 > 0) {
        self.runMilliseconds = true;
        self.countdown.minutes = Math.floor(dat2 / 60);
        if (self.countdown.minutes < 10) {
          self.countdown.minutes = '0' + self.countdown.minutes
        }
        self.countdown.seconds = Math.floor(dat2 % 60);
        if (self.countdown.seconds < 10) {
          self.countdown.seconds = '0' + self.countdown.seconds
        }
      } else {
        console.log('此次计时结束');
        clearInterval(self.intervall);
        clearInterval(self.intervall2);
        self.runMilliseconds = false;
        self.countdown.Milliseconds = '00';
        let data = { 'status': false };
        this.viewCtrl.dismiss(data);
      }
      this.changeDetectorRef.detectChanges();//检测变化
    }, 1000)
  }


  // 确认按键
  dismiss() {
    if (this.hasBindTel) {
      if (this.nextOpenTime > 10) {
        if (this.buyTypeNum == 0 && this.buyBigOrSmall == 0) {
          this.appService.alert('尊敬的用户，请您至少选择一种玩法！')
        } else {
          this.submitOrder()
        }
      } else {
        this.appService.alert('开奖前10s无法进行此操作')
      }
    } else {
      let data = { 'status': false, 'hasBindTel': false }
      this.appService.alert('请先绑定手机号', res => {
        this.viewCtrl.dismiss(data);
      })
    }
  }
  // 用户余额和是否绑定手机号
  getUserInfo() {
    this.appService.getUserInfo(this.userId, res => {
      console.log('获取用户信息 用户id:',this.userId)
      if (res.code == 1) {
        this.money = res.data.money;
        res.data.phone == 0 ? this.hasBindTel = false : this.hasBindTel = true;
      }
    })
  }
  //提交订单
  submitOrder() {
    this.order_all_price();
    let data = { 'status': true }
    let params = { sub: 'sub', goodid: this.goodId, userid: this.userId, is_dans: this.buyTypeNum, is_dax: this.buyBigOrSmall, beishu: this.num, one_price: this.goodInfo.price, price: this.order_all_prices }
    console.log(params)
    this.appService.showPrompt2(`购买倍数:  ${this.num},  支付金额:  ${this.order_all_prices}元`, res => {
      if (res) {
        this.appService.post('/apibuyorder/sub_order', params, res => {
          console.log(res)
          if (res.code == 1) {
            this.money = res.data.money;
            this.appService.alert(`操作成功`, () => {
              this.onLeave();
              setTimeout(() => {
                this.viewCtrl.dismiss(data);
              }, 50);
            })
          } else if (res.code == 0) {
            this.appService.alert(`操作失败：${res.msg}`)
          }
        })
      } else {
        console.log('取消购买操作')
      }
    })
  }

  // 模拟毫秒倒计时
  setMilliseconds() {
    clearInterval(this.intervall2)
    this.intervall2 = '';
    this.milliseconds = 98;
    this.intervall2 = setInterval(() => {
      if (self.runMilliseconds) {
        self.milliseconds -= 11;
        self.countdown.Milliseconds = self.milliseconds;
        if (self.milliseconds < 10) {
          self.countdown.Milliseconds = '0' + self.milliseconds;
        }
        if (self.milliseconds <= 0) {
          self.countdown.Milliseconds = '00';
          self.milliseconds = 98
        }
      } else {
        self.countdown.Milliseconds = '00';
      }
    }, 100)
  }
  // 设置结束时间
  setEndTime(lastTime) {
    let endTime = new Date().getTime() + lastTime * 1000
    this.CountDown(endTime)
  }

}
